package ceura.ia.practica.android;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;
import ceura.ia.practica.android.brush.BackgroundType;

import ceura.ia.practica.android.ui.Celda;
import ceura.ia.practica.android.ui.LaberintoView;
import ceura.ia.practica.properties.Propiedades;

/**
 * Actividad principal del proyecto.
 *
 * @author Jorge Madrid y Sergio Redondo.
 */
public class AStar extends Activity implements OnMenuItemClickListener {

    private Propiedades properties;
    private LaberintoView laberintoView;

    /**
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        properties = Propiedades.getInstance();

        initMetrics();

        laberintoView = new LaberintoView(this);

        setContentView(laberintoView.getNewLaberintoView());

        ActionBar ab = getActionBar();
        ab.hide();
        showHelp();
    }

    private void showHelp() {
        AlertDialog.Builder alert = new AlertDialog.Builder(AStar.this);
        LayoutInflater inflater = (LayoutInflater) AStar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.vista_ayuda, null);
        alert.setView(v);
        alert.setNeutralButton("Aceptar", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        alert.show();
    }

    private void initMetrics() {
        //para conseguir el px, el tamaño de la pantalla
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        properties.initWindow(metrics.widthPixels, metrics.heightPixels);
    }

    /**
     * Muestra un menu con más opciones de configuración.
     *
     * @param v La vista del menu a inflar.
     */
    public void showPopup(View v) {
        PopupMenu popup = new PopupMenu(this, v);
        MenuInflater inflater = popup.getMenuInflater();
        popup.setOnMenuItemClickListener(this);
        inflater.inflate(R.menu.menu_barra_superior, popup.getMenu());
        popup.show();
    }

    private void modificarTamañoCeldas(int numCeldas) {
        GridLayout gridLayout = laberintoView.getGridLayout();
        gridLayout.removeAllViews();
        properties.numCol = numCeldas;
        properties.numRow = numCeldas;
        gridLayout.setRowCount(numCeldas);
        gridLayout.setColumnCount(numCeldas);
        for (int i = 0; i < numCeldas * numCeldas; i++) {
            Celda celda = new Celda(gridLayout.getContext(), i);
            gridLayout.addView(celda, i);
        }
    }

    private void sacarCambio() {
        final AlertDialog.Builder alert = new AlertDialog.Builder(AStar.this);
        LayoutInflater inflater = (LayoutInflater) AStar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View v = inflater.inflate(R.layout.style_cambio_columnas, null);
        alert.setView(v);
        alert.setTitle("Tamaño del laberinto");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText inputNumCeldas = (EditText) v.findViewById(R.id.txtNumCeldas);
                String valueNumCeldas = inputNumCeldas.getText().toString();
                int celdas = Integer.parseInt(valueNumCeldas);
                if (!valueNumCeldas.equals("") && celdas < 60) {
                    modificarTamañoCeldas(Integer.parseInt(valueNumCeldas));
                } else {
                    Toast.makeText(alert.getContext(), "No puedes tener campos vacios ni pasarte de 60", Toast.LENGTH_SHORT).show();
                }
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        });
        alert.show();
    }

    private void modificarTiempoEspera() {
        final AlertDialog.Builder alert = new AlertDialog.Builder(AStar.this);
        LayoutInflater inflater = (LayoutInflater) AStar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View v = inflater.inflate(R.layout.cambio_sleep, null);
        alert.setView(v);
        alert.setTitle("Cambiar tiempo de espera");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText inputColumnas = (EditText) v.findViewById(R.id.txtSleep);
                String sleep = inputColumnas.getText().toString();
                long sleepTime = Long.parseLong(sleep);
                laberintoView.setSleepTime(sleepTime);
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        });
        alert.show();
    }

    /**
     * Click listener del menu avanzado de opciones.
     *
     * @param item El item clickeado del menu.
     * @return Si se debe continuar con la propagación del evento.
     */
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.redimensionar:
                sacarCambio();
                break;
            case R.id.sleep:
                modificarTiempoEspera();
                break;
            case R.id.reset:
                reset(BackgroundType.CAMINO);
                break;
            case R.id.limpiar:
                reset(null);
                break;
            case R.id.ayuda:
                showHelp();
                break;
        }
        return true;
    }

    private void reset(BackgroundType type) {
        GridLayout gridLayout = laberintoView.getGridLayout();
        int columnCount = gridLayout.getColumnCount();
        int rowCount = gridLayout.getRowCount();
        for (int i = 0; i < columnCount * rowCount; i++) {
            Celda celda = (Celda) gridLayout.getChildAt(i);
            if (type == null) {
                celda.reset();
            } else {
                if (celda.getBackgroundType() == type) {
                    celda.reset();
                }
            }
        }
    }
}
